package com.hxgz.steel.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxgz.steel.common.ResponseCode;
import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.dao.CategoryMapper;
import com.hxgz.steel.dao.ProductMapper;
import com.hxgz.steel.dao.ProductModelMapper;
import com.hxgz.steel.dao.ProductParameterMapper;
import com.hxgz.steel.domain.*;
import com.hxgz.steel.dto.CategoryDto;
import com.hxgz.steel.dto.ExtendGoodDto;
import com.hxgz.steel.dto.GoodDto;
import com.hxgz.steel.service.GoodsManageService;
import com.hxgz.steel.util.CommonUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author liuhuan
 * @description  商品管理业务层
 * @date 2019/1/22
 */
@Service
public class GoodsManageServiceImpl implements GoodsManageService{

    @Autowired
    ProductMapper mapper;
    @Autowired
    ProductModelMapper pmMapper;
    @Autowired
    ProductParameterMapper ppMapper;
    @Autowired
    CategoryMapper cMapper;

    /**
     * 页面初始化
     * @param id 1-风类("default")  2-水类  3-电类  4-消防类
     * @return
     */
    public ServerResponse init(Integer id){
        Map map = new HashMap();
        //查询材质
        map.put("metrails",getDown("材质",id));
        //查询规格
        map.put("spec",getDown("规格",id));
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse insertPage(Integer id) {
        Map map = new HashMap();
        //查询材质
        map.put("materials",getDown("材质",id));
        //查询规格
        map.put("spec",getDown("规格",id));
        //商品名称
        map.put("name",getDown("商品名称",id));

        map.put("topName",getDown("品名",id));
        return ServerResponse.createBySuccess(map);
    }

    /**
     *  common  获取下拉数据
     * @param name  品名，商品名称，材质，特性
     * @param id 1-风类  2-水类  3-电类  4-消防类
     * @return
     */
    @Override
    public List<CategoryDto> getDown(String name, Integer id){
        List<CategoryDto> metDtoList = cMapper.selectMetrails(name,id);
        if(metDtoList == null || metDtoList.isEmpty()){
            metDtoList = new ArrayList<CategoryDto>();
        }
        return metDtoList;
    }

    /**
     * 商品列表
     * @return
     */
    @Override
    public ServerResponse listGoods( GoodDto dto,Page page) {
        PageHelper.startPage(page.getCurrPageNo(),page.getPageSize());
        List<ExtendGoodDto> list = mapper.listProducts(dto);
        PageInfo info= new PageInfo(list);
        return ServerResponse.createBySuccess(info);
    }

    /**
     * 新增商品
     * @param product  商品
     * @param productModel 商品型号
     * @param productParameter 商品参数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse insertProduct(Product product, String productModel, String productParameter) {
        int num =0;
        product.setUpdateTime(new Date());
        if(product.getId() ==null){
            product.setCreateTime(new Date());
            product.setProductCode(CommonUtils.generateUUID());
            //新增商品
            num = mapper.insertProduct(product);
        }else{
            num = mapper.updateProduct(product);
            //删除之前的商品型号和商品参数hotProduct.do
            pmMapper.deleteByProductId(product.getId());
            ppMapper.deleteByProductId(product.getId());
        }
        //新增商品型号
        JSONArray jarray = JSONArray.parseArray(productModel);
        for (int i = 0; i < jarray.size(); i++) {
            JSONObject job = jarray.getJSONObject(i);
            ProductModel model = new ProductModel();
            model.setColor(job.getString("color"));
            model.setModel(job.getString("model"));
            model.setPrice(job.getBigDecimal("price"));
            model.setProductId(product.getId());
            pmMapper.insertSelective(model);
        }
        //新增商品参数
        JSONArray parameter = JSONArray.parseArray(productParameter);
        for (int i = 0; i < parameter.size(); i++) {
            JSONObject job1 = parameter.getJSONObject(i);
            ProductParameter proPram = new ProductParameter();
            proPram.setName(job1.getString("name"));
            proPram.setInfo(job1.getString("info"));
            proPram.setProductId(product.getId());
            ppMapper.insertSelective(proPram);
        }
        return num == 1 ? ServerResponse.createBySuccessMessage("操作成功") : ServerResponse.createByErrorMessage("操作失败");
    }

    /**
     * 查询商品信息明细
     * @param occasionProduct
     * @return
     */
    @Override
    public ServerResponse<Map<String,Object>> selectProductInfo(Product occasionProduct) {
        Map<String,Object> map = new HashMap();
        //查询商品表信息
        ProductWithBLOBs product = mapper.getProductById(occasionProduct.getId());
        if(StringUtils.isNotBlank(product.getSubImages())){
            String[] split = product.getSubImages().split(";");
            if(split.length!=0){
                product.setSubImagesList(Arrays.asList(split));
            }else{
                product.setSubImagesList(new ArrayList<>());
            }
        }else{
            product.setSubImagesList(new ArrayList<>());
        }
        //根据商品id查询商品销量
        Integer integer = mapper.getProductSales(product.getId());
        product.setTotalSale(integer);
        if (product.getFreight()==null||"".equals(product.getFreight())){
            product.setFreight(new BigDecimal(0));
        }
        map.put("product",product);
        //查询商品型号
        List<ProductModel> pModelList = pmMapper.listModelsByProId(occasionProduct.getId());
        if (pModelList == null || pModelList.isEmpty()){
            ProductModel model = new ProductModel();
            pModelList.add(model);
        }
        map.put("pModelList",pModelList);
        //查询商品参数
        List<ProductParameter> ppList = ppMapper.listParameterByProId(occasionProduct.getId());
        if(ppList ==null || ppList.isEmpty()){
            ProductParameter pp = new ProductParameter();
            ppList.add(pp);
        }
        map.put("ppList",ppList);
        //查询条件下拉
        map.put("topName",getDown("品名",occasionProduct.getCategoryId()));
        map.put("name",getDown("商品名称",occasionProduct.getCategoryId()));
        map.put("metrails",getDown("材质",occasionProduct.getCategoryId()));
        map.put("features",getDown("规格",occasionProduct.getCategoryId()));
        return ServerResponse.createBySuccess(map);
    }

    /**
     * 商品(批量)上架/下架/删除
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse updateStatusByUserIdAndId(Long userId,String ids,Integer status){
        Product product = null;
        String [] str = ids.split(",");
        int countChange =0;
        for(int i=0;i<str.length;i++){
            product = new Product();
            product.setUserId(userId);
            product.setStatus(status);
            product.setId(Long.valueOf(str[i]));
            int change = mapper.updateStatusByUserIdAndId(product);
            countChange += change;
        }
        return str.length == countChange ? ServerResponse.createBySuccessMessage("操作成功"):ServerResponse.createByErrorMessage("操作失败");
    }
}
